/*
	The MIT License

	Copyright (c) 2008 IFMO/GameDev Studio

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.
*/
// gui_manager.cpp - 

#include "ui_local.h"


const float VIRTUAL_WIDTH	=	1280.0f;
const float VIRTUAL_HEIGHT	=	720.0f;

/*-----------------------------------------------------------------------------
	Frame Manager
-----------------------------------------------------------------------------*/

//
//	EGUIManager::EGUIManager
//
EGUIManager::EGUIManager(EUserInterface *ui)
{
	this->ui	=	ui;
	con		=	ui->con;
	shell	=	ui->shell;
	fs		=	ui->fs;
	rs		=	ui->rs;
	
	uint w, h;
    rs->GetScreenSize(w, h);
    mouse_x = w/2;
    mouse_y = h/2;
	
	shell->AddCommand("guiCreate",		(EShellCmd_f)GuiCreate_f,		this);
	shell->AddCommand("guiAttach",		(EShellCmd_f)GuiAttach_f,		this);
	shell->AddCommand("guiSetLayout",	(EShellCmd_f)GuiSetLayout_f,		this);
	shell->AddCommand("guiRearrange",	(EShellCmd_f)GuiRearrange,		this);
	shell->AddCommand("guiReadConfig",	(EShellCmd_f)GuiReadConfig_f,	this);
	shell->AddCommand("guiWriteConfig",	(EShellCmd_f)GuiWriteConfig_f,	this);
	
	mb_down_frame[0]	= NULL;
	mb_down_frame[1]	= NULL;
	mb_down_frame[2]	= NULL;
	frame_under_cursor	= NULL;
	active_frame		= NULL;
	
	branch_color_stack.push(EVec4(1,1,1,1));

	//	create root frame :	
	//w = VIRTUAL_WIDTH;
	//h = VIRTUAL_HEIGHT;
	decor	=	new EGUIDecoration(this, "global");
	root	=	new EGUIFrame(this, "root", 0, 0, (float)w, (float)h);
	RegisterEntity(root);
	RegisterEntity(decor);

	//	Load UI from config file :
	shell->ExecuteConfig("scripts/ui.cfg");
}


//
//	EUIFrameImage::~EUIFrameImage
//
EGUIManager::~EGUIManager(void)
{
	for (uint i=0; i<entities.size(); i++) {
		delete entities[i];
	}
	
	entities.clear();
}


void EGUIManager::Activate(void)
{
}

void EGUIManager::Deactivate(void)
{
}


void EGUIManager::SetBranchColor(const EVec4 &color)
{
	EVec4 current_color = branch_color_stack.top();
	current_color *= color;
	branch_color_stack.push(current_color);
	rs->Set2DColor(current_color);
}


void EGUIManager::RevertBranchColor(void)
{
	branch_color_stack.pop();
	EVec4 current_color = branch_color_stack.top();
	rs->Set2DColor(current_color);
}


void EGUIManager::ResetView(void)
{
	rs->Set2DViewMode(0, 0);
	SetOffset(0, 0);
}

void EGUIManager::SetOffset(float dx, float dy)
{
	rs->SetTransform( Matrix4Translate(EVec4(dx, dy, 0, 0)) );
}


//
//	EGUIManager::Draw
//
void EGUIManager::Draw(void)
{
    uint w, h;
    rs->GetScreenSize(w, h);

    ResetView();

	DrawFrameRecursive(root);    
	ProcessRecursive(root);
    
    ResetView();

	IImage	*cursor = rs->RegisterImage("ui/cursor.tga");
	int img_x = cursor->GetWidth();
	int img_y = cursor->GetHeight();
	rs->DrawImage(mouse_x - img_x/2.0f, mouse_y - img_y/2.0f, "ui/cursor.tga");
}


//
//	EGUIManager::DrawFrameRecursive
//
void EGUIManager::DrawFrameRecursive(EGUIFrame *frame)
{
	if (!frame->IsVisible()) {
		return;
	}

	float x, y;
	GetAbsolutePosition(frame->GetParent(), x, y);
	
	ResetView();
	SetOffset(x,y);
	
	SetBranchColor(EVec4(1,1,1, frame->GetFrameOpacity()));
	
	frame->FMPaint();
	
	for (uint i=0; i<frame->GetChildNum(); i++) {	
		DrawFrameRecursive( frame->GetChild(i) );
	}
	
	RevertBranchColor();

	ResetView();
}


void EGUIManager::ProcessRecursive(EGUIFrame *frame)
{
	frame->FMProcess(ui->core->GetDeltaTime(), ui->sys->Milliseconds()/1000.0f);
	
	for (uint i=0; i<frame->GetChildNum(); i++) {	
		ProcessRecursive( frame->GetChild(i) );
	}
}


//
//	EGUIManager::KeyPress
//
void EGUIManager::KeyPress(uint code)
{
	if (active_frame) {
		active_frame->FMKeyPress(code);
	}
}


//
//	EGUIManager::KeyDown
//
void EGUIManager::KeyDown(uint code)
{
	if (active_frame) {
		active_frame->FMKeyDown(code);
	}
}


//
//	EGUIManager::MouseMove
//
void EGUIManager::MouseMove(const mouseInput_s *mi)
{
	mouse_x	= mi->x;
	mouse_y	= mi->y;
	
	EGUIFrame	*current_frame_uc = GetFrameUnderCursor();
	
	//
	//	Handle Mouse Button Events :
	//
	bool mb_down[3];
	bool mb_up[3];

	mb_down[0]	=	!old_mouse.left && mi->left;
	mb_up[0]	=	old_mouse.left && !mi->left;
	mb_down[1]	=	!old_mouse.right && mi->right;
	mb_up[1]	=	old_mouse.right && !mi->right;
	mb_down[2]	=	!old_mouse.middle && mi->middle;
	mb_up[2]	=	old_mouse.middle && !mi->middle;
	
	for (uint button=0; button<3; button++) {
		float x, y;
		GetAbsolutePosition( current_frame_uc, x, y);
		
		// MOUSE BUTTON DOWN :
		if (mb_down[button]) {
			//	send MouseDown message :
			if (current_frame_uc) {
				current_frame_uc->FMMouseDown(0, mouse_x - x, mouse_y - y);
			}

			// we should remember frame to handle MouseClick :
			mb_down_frame[button]	=	current_frame_uc;
		}
		
		//	MOUSE BUTTON UP :
		if (mb_up[button]) {
		
			//	send MouseUp message :
			if (current_frame_uc) {
				current_frame_uc->FMMouseUp(0, mouse_x - x, mouse_y - y);
			}

			//	handle MouseClick :
			if (current_frame_uc==mb_down_frame[button]) {
				if (current_frame_uc) {
					current_frame_uc->FMMouseClick(0, mouse_x - x, mouse_y - y);
				}
			}
		}
	}

	//
	//	Handle Mouse Moving Events :
	//
	if (frame_under_cursor != current_frame_uc) {
		if (frame_under_cursor) {
			frame_under_cursor->FMMouseOut();
		}
		if (current_frame_uc) {
			current_frame_uc->FMMouseIn();
		}
	}
	
	//
	//	Update old values :
	//
	frame_under_cursor	=	current_frame_uc;	
	old_mouse			=	*mi;
}


//
//	EGUIManager::RegisterFrame
//
void EGUIManager::RegisterEntity(EGUIEntity *entity)
{
	if (FindEntity(entity->GetName())) {
		RAISE_EXCEPTION(va("GUI entity %s is already registered", entity->GetName()));
	}

	entities.push_back(entity);
}


//
//	EGUIManager::FindFrame
//	- return pointer to frame
//
EGUIEntity *EGUIManager::FindEntity(const char *name)
{
	for (uint i=0; i<entities.size(); i++) {	
		if (strcmp(entities[i]->GetName(), name)==0) {
			return entities[i];
		}
	}
	return NULL;
}


//
//	EGUIManager::GetAbsolutePosition
//
void EGUIManager::GetAbsolutePosition(EGUIFrame *frame, float &x, float &y)
{
	// TODO : look for decomposition!
	if (!frame) {
		x = y = 0;
		return;
	}
	
	EGUIFrame *f = frame->GetParent();
	
	uiRect_s r = frame->GetClientRect();
	x = r.x;
	y = r.y;
	
	while (f) {
		uiRect_s r = f->GetClientRect(); 
		float dx = r.x; 
		float dy = r.y;
		x += dx;
		y += dy;
		f = f->GetParent();
	}
}


//
//	EGUIManager::GetFrameUnderCursor
//
static bool IsInRect(float cx, float cy, float x, float y, float w, float h)
{
	if (cx<x) return false;
	if (cy<y) return false;
	if (cx>x+w) return false;
	if (cy>y+h) return false;
	return true;
}


EGUIFrame *EGUIManager::GetFrameUnderCursor(void)
{
	float cur_x = (float)mouse_x;
	float cur_y = (float)mouse_y;
	
	EGUIFrame *top = root;
	
	
	_begin:
	//for (uint i=0; i<top->GetChildNum(); i++) 
	for (int i=top->GetChildNum()-1; i>=0; i--) 
	{
		// TODO : Check visibility!!!
		EGUIFrame *child = top->GetChild(i);
		
		if (!child->IsEnabled()) continue;
		
		float x,y,w,h;
		
		GetAbsolutePosition(child, x, y);
		uiRect_s r = child->GetClientRect();
		w = r.w;
		h = r.h;
		
		if (IsInRect(cur_x, cur_y, x, y, w, h))
		{
			top = child;
			goto _begin;
		}
	}
	return top;
}


void EGUIManager::SetForegroundFrame(EGUIFrame *frame)
{
	EGUIFrame *f = frame;
	while(f != root) {
		f->GetParent()->SetForeground(f);
		f = f->GetParent();
	}
}


void EGUIManager::SetActiveFrame(EGUIFrame *frame)
{
	active_frame = frame;
}


EGUIFrame *EGUIManager::GetActiveFrame(void)
{
	return active_frame;
}



/*-----------------------------------------------------------------------------
	UI Creation Console Functions :
-----------------------------------------------------------------------------*/

void EGUIManager::GuiCreate_f(EGUIManager *self, int argc, char **argv)
{
	IConsole	*con = self->con;
	if (argc!=7 && argc!=3) {
		LOGF("usage: guiCreate <class> <name> <x> <y> <width> <height>\r\n");
		LOGF("   or: guiCreate <class> <name>\r\n");
		return;
	}
	
	const char *clsname = argv[1];
	const char *name    = argv[2];
	
	float x=0, y=0, w=10, h=10;
	if (argc==7) {
		x = (float)atof(argv[3]);
		y = (float)atof(argv[4]);
		w = (float)atof(argv[5]);
		h = (float)atof(argv[6]);
	}
	
	EGUIEntity *new_entity = NULL;
	
	//LOGF("%s %s %s\r\n", argv[0], argv[1], argv[2]);

	//	TODO : remove "switch-like" construction!	
	if (strcmp(clsname, "FRAME")==0) {
		new_entity = new EGUIFrame(self, name, x, y, w, h);
	}
	
	if (strcmp(clsname, "WINDOW")==0) {
		new_entity = new EGUIWindow(self, name, x, y, w, h);
	}
	
	if (strcmp(clsname, "BUTTON")==0) {
		new_entity = new EGUIButton(self, name, x, y, w, h);
	}
	
	if (strcmp(clsname, "CONTROL")==0) {
		new_entity = new EGUIControl(self, name, x, y, w, h);
	}

	if (strcmp(clsname, "EDITBOX")==0) {
		new_entity = new EGUIEditBox(self, name, x, y, w, h);
	}
	
	if (strcmp(clsname, "CHECKBOX")==0) {
		new_entity = new EGUICheckBox(self, name, x, y, w, h);
	}
	
	if (strcmp(clsname, "SLIDER")==0) {
		new_entity = new EGUISlider(self, name, x, y, w, h);
	}
	
	
	//	LAYOUTS :
	if (strcmp(clsname, "VERTICAL_LAYOUT")==0) {
		new_entity = new EGUIVerticalLayout(self, name);
	}
	
	if (strcmp(clsname, "HORIZONTAL_LAYOUT")==0) {
		new_entity = new EGUIHorizontalLayout(self, name);
	}
	
	if (strcmp(clsname, "BORDER_LAYOUT")==0) {
		new_entity = new EGUIBorderLayout(self, name);
	}
	
	if (new_entity) {
		EGUIFrame *frame = dynamic_cast<EGUIFrame*>(new_entity);
		self->RegisterEntity(new_entity);
	}
}


void EGUIManager::GuiAttach_f(EGUIManager *self, int argc, char **argv)
{
	IConsole	*con = self->con;
	if (argc!=3 && argc!=4) {
		LOGF("usage: guiAttach <parent> <child>\r\n");
		LOGF("usage: guiAttach <parent> <child> <layout id>\r\n");
		return;
	}
	
	const char *parent = argv[1];
	const char *child  = argv[2];
	EGUIFrame *parent_frame = dynamic_cast<EGUIFrame*>(self->FindEntity(parent));
	EGUIFrame *child_frame  = dynamic_cast<EGUIFrame*>(self->FindEntity(child));
	
	uint layout_id = 0;
	if (argc==4) {
		layout_id = atoi(argv[3]);
	}
	
	if (!parent_frame) {
		RAISE_EXCEPTION(va("Frame %s is not registered", parent));
	}
	if (!child_frame) {
		RAISE_EXCEPTION(va("Frame %s is not registered", child));
	}

	child_frame->SetLayoutIndex(layout_id);	
	parent_frame->Attach(child_frame);
}


void EGUIManager::GuiSetLayout_f(EGUIManager *self, int argc, char **argv)
{
	IConsole	*con = self->con;
	if (argc!=3) {
		LOGF("usage: guiSetLayout <frame> <layout>\r\n");
		return;
	}
	
	EGUIFrame  *frame	= dynamic_cast<EGUIFrame*> (self->FindEntity(argv[1]));
	EGUILayout *layout  = dynamic_cast<EGUILayout*>(self->FindEntity(argv[2]));
	
	if (!frame) {
		RAISE_EXCEPTION(va("Frame %s is not registered", argv[1]));
	}
	if (!layout) {
		RAISE_EXCEPTION(va("Layout %s is not registered", argv[2]));
	}
	
	frame->SetLayout(layout);
}


void EGUIManager::GuiRearrange(EGUIManager *self, int argc, char **argv)
{
	for (uint i=0; i<self->entities.size(); i++) 
	{
		EGUIFrame *frame = dynamic_cast<EGUIFrame*>(self->entities[i]);

		if (frame) {
			uiRect_s r = frame->GetFrameRect();
			frame->FMMove(r.x, r.y);
			frame->FMResize(r.w, r.h);
		}
	}
}


void EGUIManager::GuiReadConfig_f(EGUIManager *self, int argc, char **argv)
{
	for (uint i=0; i<self->entities.size(); i++) {
		EGUIFrame *frame = dynamic_cast<EGUIFrame*>(self->entities[i]);

		if (frame) {
			frame->FMCtrlReadConfig();
		}
	}
}


void EGUIManager::GuiWriteConfig_f(EGUIManager *self, int argc, char **argv)
{
	for (uint i=0; i<self->entities.size(); i++) {
		EGUIFrame *frame = dynamic_cast<EGUIFrame*>(self->entities[i]);

		if (frame) {
			frame->FMCtrlWriteConfig();
		}
	}
}

/*-----------------------------------------------------------------------------
	UI Frame Entity
-----------------------------------------------------------------------------*/

EGUIEntity::EGUIEntity(EGUIManager *fm, const char *name)
{
	this->name	=	name;
	this->ui	=	fm->ui;
	this->fm	=	fm;
	
	con		=	ui->con;
	shell	=	ui->shell;
	rs		=	ui->rs;
	fs		=	ui->fs;
}


EGUIEntity::~EGUIEntity(void)
{
}


const char *EGUIEntity::GetName(void) const
{
	return name.c_str();
}


const char *EGUIEntity::ObjName(const char *name) const
{
	return va("%s::%s", this->name.c_str(), name);
}


/*-----------------------------------------------------------------------------
	Abstract Frame :
-----------------------------------------------------------------------------*/

EGUIFrame::EGUIFrame(EGUIManager *fm, const char *name, float x, float y, float w, float h)
 : EGUIEntity(fm, name)
{
	parent	=	NULL;
	SetDecoration(fm->GetDecoration());
	SetLayout(NULL);
	SetLayoutIndex(0);
	
	frame_rect.x	=	x;
	frame_rect.y	=	y;
	frame_rect.w	=	w;
	frame_rect.h	=	h;
	frame_opacity	=	1;
		
	FMResize(w, h);
	FMMove(x, y);
	
	FMShowFrame();
	
	shell->AddCommand(ObjName("show"),		(EShellCmd_f)Show_f,	this);
	shell->AddCommand(ObjName("hide"),		(EShellCmd_f)Hide_f,	this);
	shell->AddCommand(ObjName("setAlign"),	(EShellCmd_f)SetAlign_f,	this);
	
/*	on_mouse_click		=	shell->RegisterVar(ObjName("on_mouse_click"),	"",		SHLF_NEW|SHLF_NOSAVE);
	on_mouse_in			=	shell->RegisterVar(ObjName("on_mouse_in"),		"",		SHLF_NEW|SHLF_NOSAVE);
	on_mouse_out		=	shell->RegisterVar(ObjName("on_mouse_out"),		"",		SHLF_NEW|SHLF_NOSAVE);	*/
}


EGUIFrame::~EGUIFrame(void)
{
}


void EGUIFrame::SetAlign_f(EGUIFrame *self, int argc, char **argv)
{
	IConsole	*con = self->con;
	if (argc!=3) {
		LOGF("usage: setAlign <mode> <spacing>\r\n");
		return;
	}
	
	self->align_mode	=	GUI_ALIGN_FREE;
	self->align_spacing	=	0;
	
	if (strcmp(argv[1], "FREE")==0)		self->align_mode = GUI_ALIGN_FREE;
	if (strcmp(argv[1], "MAX")==0)		self->align_mode = GUI_ALIGN_MAX;
	if (strcmp(argv[1], "CENTER")==0)	self->align_mode = GUI_ALIGN_CENTER;
	if (strcmp(argv[1], "LEFT")==0)		self->align_mode = GUI_ALIGN_LEFT;
	if (strcmp(argv[1], "RIGHT")==0)	self->align_mode = GUI_ALIGN_RIGHT;
	if (strcmp(argv[1], "BOTTOM")==0)	self->align_mode = GUI_ALIGN_BOTTOM;
	if (strcmp(argv[1], "TOP")==0)		self->align_mode = GUI_ALIGN_TOP;
	
	self->align_spacing	=	(float)atof(argv[2]);
}


void EGUIFrame::Align(void)
{
	if (align_mode==GUI_ALIGN_FREE) {
		return;
	}

	EGUIFrame *parent = GetParent();	
	
	if (!parent) {
		return;
	}
	
	float s = align_spacing;

	uiRect_s pr = parent->GetClientRect();
	uiRect_s r  = GetFrameRect();
	
	float x,y,w,h;
	x = frame_rect.x;
	y = frame_rect.y;
	w = frame_rect.w;
	h = frame_rect.h;
	
	if (align_mode==GUI_ALIGN_CENTER) {	
		x = (pr.w - r.w) / 2.0f;
		y = (pr.h - r.h) / 2.0f;
	} else 
	if (align_mode==GUI_ALIGN_LEFT) {	
		x = s;
		y = s;
		w = r.w;
		h = pr.h - 2 * s;
	} else 
	if (align_mode==GUI_ALIGN_RIGHT) {	
		x = pr.w - r.w - s;
		y = s;
		w = r.w;
		h = pr.h - 2 * s;
	} else 
	if (align_mode==GUI_ALIGN_TOP) {	
		x = s;
		y = s;
		w = pr.w - 2 * s;
		h = r.h;
	} else 
	if (align_mode==GUI_ALIGN_BOTTOM) {	
		x = s;
		y = pr.h - r.h - s;
		w = pr.w - 2 * s;
		h = r.h;
	} else 
	if (align_mode==GUI_ALIGN_MAX) {	
		x = s;
		y = s;
		w = pr.w - 2 * s;
		h = pr.h - 2 * s;
	} else 
	{
		return;
	}
	
	frame_rect.x = x;
	frame_rect.y = y;
	frame_rect.w = w;
	frame_rect.h = h;
	
	if (layout) {
		layout->ArrangeControls(this);
	}
}


void EGUIFrame::FMMouseClick(uint button, float x, float y)
{
	fm->SetForegroundFrame(this);
	fm->SetActiveFrame(this);
}


void EGUIFrame::FMMove(float new_x, float new_y)
{
	frame_rect.x = new_x;
	frame_rect.y = new_y;

	if (layout) {
		layout->ArrangeControls(this);
	}
	
	Align();
}


void EGUIFrame::FMResize(float new_width, float new_height)
{
	frame_rect.w = new_width;
	frame_rect.h = new_height;
	
	if (layout) {
		layout->ArrangeControls(this);
	}

	Align();
}


void EGUIFrame::Attach(EGUIFrame *child)
{
	if (child->GetParent()) {
		RAISE_EXCEPTION(va("Frame %s already attached to %s", child->GetName(), child->GetParent()->GetName()));
	}
	child->parent	=	this;
	children.push_back(child);
}


void EGUIFrame::SetForeground(EGUIFrame *frame)
{
	vector<EGUIFrame*>::iterator vi;
	
	for (vi=children.begin(); vi!=children.end(); vi++)	
	{
		if ((*vi) == frame)	{
			children.erase(vi);
			children.push_back(frame);
			return;
		}
	}
}


void EGUIFrame::FMPaint(void)
{
	//	Debug stuff :
	if (ui->ui_debug->Int()) 
	{
		uiRect_s cr = GetClientRect();
		uiRect_s fr = GetFrameRect();
		
		if (fm->GetFrameUnderCursor()==this) {
			rs->DrawRectOutline(fr.x, fr.y, fr.w, fr.h, EVec4(1,1,1, 0.7f));
			rs->DrawRectOutline(cr.x, cr.y, cr.w, cr.h, EVec4(1,1,1, 0.7f));
			ui->DrawStringMT(fr.x+1, fr.y+9,   8, 8, "fonts/chars.tga", GetName(), EVec4(1,1,1, 0.5));
			ui->DrawStringMT(fr.x+1, fr.y+17,  8, 8, "fonts/chars.tga", typeid(*this).name(), EVec4(1,1,1, 0.5));
		} else {
			rs->DrawRectOutline(fr.x, fr.y, fr.w, fr.h, EVec4(1,1,1, 0.3f));
			rs->DrawRectOutline(cr.x, cr.y, cr.w, cr.h, EVec4(1,1,1, 0.3f));
		}
	}
}


void EGUIFrame::FMProcess(float delta, float time)
{
}











